package com.example.petstore.controller;

import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.User;
import com.example.petstore.domain.UserInfo;
import com.example.petstore.service.CodeService;
import com.example.petstore.service.UserInfoService;
import com.example.petstore.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

@SessionAttributes({"loginUser", "giteeCustome", "giteeReason", "giteeId", "verifyCode"})
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 用户名密码手机号登录
     * @param username
     * @param password
     * @param code
     * @param model
     * @param session
     * @return
     */
    @PostMapping("/loginByName")/*test ok*/
//    public String loginByName(@RequestBody User user, String code){   //前端用json封装
//    public String loginByName(@ModelAttribute User user, String code){  //前端提交表单 x-www-form
    public String loginByName(String username, String password, String code, ModelMap model, HttpSession session){
//        form-date ok;x-www-form ok;
//        ?xxx=xxx ok
//        json不行，username,password为null


//        判断验证码
//        String verifyCode = (String) model.getAttribute("verifyCode");
//        if(!verifyCode.equals(code)){
//            model.addAttribute("errorMsg", "验证码错误！");
////            回到登录页面
//            return "user/loginByName";
//        }

        CommonResponse commonResponse = userService.findUserByUsernameAndPassword(username, password);

        if(commonResponse.isSuccess()){
            model.addAttribute("loginUser", commonResponse.getData());
            session.setAttribute("loginUser", commonResponse.getData());
//            到首页
            return "catalog/main";
        }
        model.addAttribute("errorMsg", commonResponse.getMessage());
//        到登录页面
        return "user/loginByName";
    }

    /**
     * 去往gitee第三方登录
     * @param model
     * @return
     */
    @GetMapping("/loginByGitee")
    public String loginByGitee(ModelMap model){
        model.addAttribute("giteeCustome", "user");
        model.addAttribute("giteeReason", "login");
        return "redirect:https://gitee.com/oauth/authorize?client_id=ba92f844c06bf93080ad7fc1b86468a002305bc1a859e753eaffdf0d712b9351&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2FbindPhoneNumber&response_type=code";
    }

    /**
     * 手机号登录
     * @param phoneNumber
     * @param phoneCode
     * @param model
     * @return
     */
    @PostMapping("/loginByPhone")
    public String loginByPhone(String phoneNumber, String phoneCode, ModelMap model){
        CommonResponse commonResponse = userService.loginByPhone(phoneNumber, phoneCode);
        if(commonResponse.isSuccess()){
            model.addAttribute("loginUser", commonResponse.getData());
//            到首页
            return "catalog/main";
        }
        model.addAttribute("errorMsg", commonResponse.getMessage());
//        到登录页面
        return "user/loginByPhone";
    }

    /**
     * 用户登录时发送手机验证码
     * @param phoneNumber
     * @return
     */
    @GetMapping("/sendPhoneCodeForUserLogin")
    @ResponseBody
    public CommonResponse sendPhoneCodeForUserLogin(String phoneNumber){
        return codeService.sendPhoneCodeForUser(phoneNumber, "login");
    }

    /**
     * 用户注册时发送手机验证码
     * @param phoneNumber
     * @return
     */
    @GetMapping("/sendPhoneCodeForUserRegister")
    @ResponseBody
    public CommonResponse sendPhoneCodeForUserRegister(String phoneNumber){
        return codeService.sendPhoneCodeForUser(phoneNumber, "register");
    }

    /**
     * 重置密码时发送验证码
     * @param phoneNumber
     * @return
     */
    @GetMapping("/sendPhoneCodeForUserResetPassword")
    @ResponseBody
    public CommonResponse sendPhoneCodeForUserResetPassword(String phoneNumber){
        return codeService.sendPhoneCodeForUser(phoneNumber, "reset");
    }

    /**
     * 进入重置密码页面
     * @return
     */
    @GetMapping("/resetPasswordForm")
    public String resetPasswordForm(){
        return "user/resetPassword";
    }

    /**
     * 重置密码
     * @param phoneNumber
     * @param password
     * @param phoneCode
     * @param model
     * @return
     */
    @PostMapping("/resetPassword")
    public String resetPassword(String phoneNumber, String password, String phoneCode, ModelMap model){
        CommonResponse commonResponse = userService.resetPassword(phoneNumber, password, phoneCode);
        if(commonResponse.isSuccess()){
            model.addAttribute("msg", commonResponse.getMessage());
//            System.out.println("到登陆了页面");
//            到登陆页面
            return "user/loginByName";
        }
        model.addAttribute("errorMsg", commonResponse.getMessage());
//            到重置密码
        return "user/resetPassword";
    }

    /**
     * 用户gitee注册后填写手机号和用户名
     * @param username
     * @param phoneNumber
     * @param phoneCode
     * @param model
     * @return
     */
    @RequestMapping("/bindPhoneNumberAndUsername")
    public String bindPhoneNumber(String username, String phoneNumber, String phoneCode, ModelMap model){
        CommonResponse commonResponse = userService.findUserByUsername(username);
        if(commonResponse.isSuccess()){
//            手机号绑定页面
            model.addAttribute("errorMsg", "用户名已被使用");
            return "user/bind";
        }

        commonResponse = userService.findUserByPhoneNumber(phoneNumber);
        if(commonResponse.isSuccess()){
//            手机号已被绑定
            model.addAttribute("errorMsg", "手机号已被绑定");
//            手机号绑定页面
            return "user/bind";
        }

//        判断验证码是否合法
        commonResponse = codeService.checkPhoneCodeForUserRegister(phoneNumber, phoneCode);
        if(commonResponse.isSuccess()){
//            验证码合法
            String giteeid = (String) model.getAttribute("giteeId");
//            创建用户
            CommonResponse commonResponse1 = userService.saveUserByPhoneNumberAndGitee(username, phoneNumber, giteeid);
            if(commonResponse1.isSuccess()) {
                model.addAttribute("loginUser", commonResponse1.getData());//                绑定成功
//                到首页
                return "catalog/main";
            }
//            绑定失败
            model.addAttribute("errorMsg", "绑定失败");
//            手机号绑定页面
            return "user/bind";
        }else{
//            手机号绑定页面
            model.addAttribute("errorMsg", commonResponse.getMessage());
            return "user/bind";
        }
    }

    /**
     * 用手机号注册
     * @param username
     * @param password
     * @param phoneNumber
     * @param phoneCode
     * @param model
     * @return
     */
    @PostMapping("/registerByPhone")
    public String registerByPhone(String username, String password, String phoneNumber, String phoneCode, ModelMap model){
//        判断用户名是否被用
        CommonResponse commonResponse = userService.findUserByUsername(username);
        if(commonResponse.isSuccess()){
            model.addAttribute("errorMsg", "用户名已被使用");
//            到注册页面
            return "user/registerBuyer";
        }
//        判断手机号是否被用
        commonResponse = userService.findUserByPhoneNumber(phoneNumber);
        if(commonResponse.isSuccess()){
            model.addAttribute("errorMsg", "手机号已被使用");
//            到注册页面
            return "user/registerBuyer";
        }
//        判断手机验证码是否正确
        commonResponse = codeService.checkPhoneCodeForUserRegister(phoneNumber, phoneCode);
        if(commonResponse.isSuccess()){
            commonResponse = userService.saveUserByPhone(username, password, phoneNumber);
            if(commonResponse.isSuccess()){
//                注册成功
                model.addAttribute("loginUser", commonResponse.getData());
                model.addAttribute("msg", "注册成功，自动登录");
//                到首页
                return "catalog/main";
            }else{
//                注册失败
                model.addAttribute("errorMsg", "注册失败");
//                到注册页面
                return "user/registerBuyer";
            }
        }else{
//            到注册页面
            model.addAttribute("errorMsg", commonResponse.getMessage());
            return "user/registerBuyer";
        }
    }

    /**
     * 去往gitee第三方登录
     * @param model
     * @return
     */
    @RequestMapping("/registerByGitee")
    public String registerByGitee(ModelMap model){
        model.addAttribute("giteeCustome", "user");
        model.addAttribute("giteeReason", "register");
        return "redirect:https://gitee.com/oauth/authorize?client_id=ba92f844c06bf93080ad7fc1b86468a002305bc1a859e753eaffdf0d712b9351&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2FbindPhoneNumber&response_type=code";
    }

    /**
     * 判断手机号是否已经被注册
     * @param phoneNumber
     * @return
     */
    @GetMapping("/findUserByPhoneNumber")
    @ResponseBody
    public CommonResponse findUserByPhoneNumber(String phoneNumber){
        CommonResponse commonResponse = userService.findUserByPhoneNumber(phoneNumber);
        if(commonResponse.isSuccess()){
            return CommonResponse.creatForSuccessMessage("手机号已注册");
        }else{
            return CommonResponse.creatForError("手机号未注册");
        }
    }

    /**
     * 判断用户名是否已经被注册
     * @param username
     * @return
     */
    @GetMapping("/findUserByUsername")
    @ResponseBody
    public CommonResponse findUserByUsername(String username){
        CommonResponse commonResponse = userService.findUserByUsername(username);
        if(commonResponse.isSuccess()){
            return CommonResponse.creatForSuccessMessage("用户名已存在");
        }else{
            return CommonResponse.creatForError("用户名不存在");
        }
    }

    /**
     * 进入信息修改页面
     * @param model
     * @return
     */
    @GetMapping("/accountForm")
    public String accountForm(ModelMap model){
        User user = (User) model.getAttribute("loginUser");
        System.out.println(user);
        CommonResponse commonResponse = userInfoService.getUserInfoByUsername(user.getUsername());
        if(commonResponse.isSuccess()){
            model.addAttribute("userInfo", commonResponse.getData());
            System.out.println(commonResponse.getData());
//            到用户信息修改页面
            return "user/changeInfo";
        }else{
            model.addAttribute("errorMsg", "出错了，请稍后再试");
//            到首页
            return "catalog/main";
        }
    }

    /**
     * 修改个人信息
     * @param userInfo
     * @param model
     * @return
     */
    @PostMapping("/changeInfo")/* need test*/
    public String postChangeInfo(@ModelAttribute UserInfo userInfo, ModelMap model){
        System.out.println(userInfo);
        User user = (User) model.getAttribute("loginUser");
//        todo:update有问题,需要测试
        CommonResponse commonResponse = userInfoService.updateUserInfo(user.getUsername(), userInfo);
        if(commonResponse.isSuccess()){
            model.addAttribute("msg", "修改成功");
            model.addAttribute("userInfo", commonResponse.getData());
            return "user/changeInfo";
        }else{
            model.addAttribute("errorMsg", "修改失败");
            return "redirect:/user/accountForm";
        }
    }

    /**
     * 进入用用户名登录页面
     * @return
     */
    @GetMapping("/loginByNameForm")
    public String loginByNameForm(){
        return "user/loginByName";
    }

    /**
     * 进入用手机号登录页面
     * @return
     */
    @GetMapping("/loginByPhoneForm")
    public String loginByPhoneForm(){
        return "user/loginByPhone";
    }

    /**
     * 退出登录
     * @param model
     * @param httpSession
     * @return
     */
    @RequestMapping("/signOut")
    public String signout(ModelMap model, HttpSession httpSession){
        model.addAttribute("loginUser", null);
//        System.out.println(model.getAttribute("loginUser"));
        httpSession.removeAttribute("loginUser");
        return "catalog/main";
    }
}
